<template>
  <pro-page class="UserLogin" aria-label="登录页面" :watermark="false">
    <section class="wrapper">
      <header class="hd">
        <!-- <img class="logo" src="@/assets/logo.png" alt="logo" /> -->
        <span class="title">{{ appName }}</span>
      </header>

      <a-form-model class="bd" ref="form" :model="form" :rules="rules" @submit.prevent="onSubmit">
        <a-form-model-item prop="username">
          <a-input
            v-model="form.username"
            class="control"
            placeholder="用户名: admin"
            autocomplete="autocomplete"
            size="large"
          >
            <a-icon slot="prefix" type="user" />
          </a-input>
        </a-form-model-item>

        <a-form-model-item prop="password">
          <a-input-password
            v-model="form.password"
            class="control"
            placeholder="密码: 1"
            autocomplete="autocomplete"
            size="large"
          >
            <a-icon slot="prefix" type="lock" />
          </a-input-password>
        </a-form-model-item>

        <a-form-model-item>
          <a-button :loading="logging" class="control" html-type="submit" type="primary" size="large" block>登录</a-button>
        </a-form-model-item>
      </a-form-model>
    </section>
  </pro-page>
</template>

<script>
import { isDev } from '@/utils/env'

export default {
  name: 'UserLogin',
  data() {
    return {
      logging: false,
      form: {
        username: isDev ? 'admin' : '',
        password: isDev ? '1' : ''
      },
      redirect: undefined,
      otherQuery: {}
    }
  },
  computed: {
    appName: () => process.env.VUE_APP_TITLE,
    rules: () => ({
      username: [ { required: true, message: '请输入账户名', trigger: [ 'change' ] } ],
      password: [ { required: true, message: '请输入密码', trigger: [ 'change' ] } ]
    })
  },
  watch: {
    $route: {
      handler(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return

        this.logging = true

        try {
          await this.$store.dispatch('user/login', this.form)
          // TODO: `vue-router@3.0.7`以上版本会报错: Redirected when going from "/login" to "/" via a navigation guard.
          // 临时方案，如果有新方案需要调整
          this.$router.push({ path: this.redirect || '/', query: this.otherQuery }).catch(() => {})
        } catch (e) {
          this.$message.error('登录失败，账户或密码错误')
        } finally {
          this.logging = false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="less" src="./index.less" />
